//
//  RecommendView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/3.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import SwiftyJSON

@objc protocol RecommendDelegate {
    
    @objc optional func showNewsDetails(model:RecommendModel) //显示推荐详情
    @objc optional func showRecommendDetails(id:String,urlStr:String,title:String) //显示申请详情
    @objc optional func changeTableViewFrame(count:Int) //改变tableView坐标
    @objc optional func stopRefresh() //停止刷新
}

class RecommendView: UIView {

    fileprivate let cellId = "recommendCell"
    
    weak var recommendDelegate : RecommendDelegate?
    
    var dataArray = [RecommendModel]()
    
    var tableView : UITableView!
    fileprivate let headView = UIView()
    
    let moreButton = UIButton() //更多
    let arrowButton = UIButton() //箭头
    
    init() {
        super.init(frame: .zero)
        
        self.backgroundColor = UIColor.mineColor()
        
        headView.backgroundColor = UIColor.white
        self.addSubview(headView)
        
        let logoImageView = UIImageView()
        logoImageView.image = #imageLiteral(resourceName: "wytj")
        headView.addSubview(logoImageView)
        
        let titleLabel = UILabel()
        titleLabel.text = recommendedByFriend
        titleLabel.font = UIFont.systemFont(ofSize: RATIO(maxNum: 16))
        headView.addSubview(titleLabel)
        
        moreButton.setTitle(moreRecommended, for: .normal)
        moreButton.setTitleColor(UIColor.black, for: .normal)
        moreButton.titleLabel?.font = UIFont.systemFont(ofSize: RATIO(maxNum: 14))
        headView.addSubview(moreButton)
        
        arrowButton.layer.contents = #imageLiteral(resourceName: "next").cgImage
        headView.addSubview(arrowButton)
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.isScrollEnabled = false //禁止滑动
        tableView.backgroundColor = UIColor.clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(RecommendCell.self, forCellReuseIdentifier: cellId)
        tableView.separatorStyle = .none
        self.addSubview(tableView)
        
        headView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
        
        logoImageView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(RATIO(maxNum: 8))
            make.centerY.equalToSuperview()
            make.width.height.equalTo(RATIO_H(maxNum: 30))
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(logoImageView.snp.right).offset(RATIO(maxNum: 8))
            make.centerY.equalToSuperview()
            make.width.greaterThanOrEqualTo(10)
            make.height.greaterThanOrEqualTo(10)
        }
        
        arrowButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(RATIO(maxNum: -8))
            make.centerY.equalToSuperview()
            make.width.equalTo(20)
            make.height.equalTo(20)
        }
        
        moreButton.snp.makeConstraints { (make) in
            make.right.equalTo(arrowButton.snp.left)
            make.centerY.equalToSuperview()
            make.width.greaterThanOrEqualTo(10)
            make.height.greaterThanOrEqualTo(10)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(headView.snp.bottom).offset(RATIO_H(maxNum: 2))
        }
        
        getData()
    }
    
    //MARK:加载数据
    public func getData() {
        
        KMTool.requestGetData(URLString: url_recommend, parameters: ["psw":"kameng98_loan","type":"1"], progress: nil, success: { (data) in
            
            do{
                let json = try JSON.init(data: data)
                if let array = json.arrayObject as? [[String:Any]] {
                    
                    self.dataArray.removeAll()
                    for i in 0..<array.count {
                        let model = RecommendModel.setModel(with: array[i])
                        self.dataArray.append(model)
                        
                        if i==7{
                            break
                        }
                    }
                    
                    self.recommendDelegate?.changeTableViewFrame!(count: self.dataArray.count)
                    self.tableView.reloadData()
                    
                }
            }catch{
                
            }
        }) {
            self.recommendDelegate?.stopRefresh!()
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension RecommendView : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 90)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? RecommendCell
        cell?.model = dataArray[indexPath.row]
        cell?.requestBtn.tag = indexPath.row
        cell?.requestBtn.addTarget(self, action: #selector(freeRecommend(sender:)), for: .touchUpInside)
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        self.recommendDelegate?.showNewsDetails!(model: dataArray[indexPath.row])
    }
    
    //MARK: 免费申请
    @objc fileprivate func freeRecommend(sender:UIButton) {
        
        var urlString = ""
        
        let model = dataArray[sender.tag]
        if model.app_apply_access != "" {
            urlString = model.app_apply_access!
        }else if model.m_apply_access != "" {
            urlString = model.m_apply_access!
        }else if model.apply_access != "" {
            urlString  = model.apply_access!
        }
        
        
        if urlString == "" {
            return
        }
        
        self.recommendDelegate?.showRecommendDetails!(id: model.id!,urlStr: urlString, title: dataArray[sender.tag].credit_name!)
    }
    
    
}
